<template>
	<view class="main" v-if="Object.keys(shops).length > 0">
		<view class="list-box" :style="{ width: windowWidth + 'px' }">
			<view
				class="list"
				v-for="(value, key) in shops"
				:key="key"
				@longpress="longpress(key, value)"
				@click.stop="handleItemClick(key, value)"
				:class="{ listactive: keyIsState(key) }"
				:style="{width: barWidth+'px'}">
				<!-- 内容保持不变 -->
				<view class="img_box" v-if="iconMap[key]">
					<image class="img" :src="iconMap[key].url || defaultIcon" mode="aspectFill" @error="handleImageError(key)"></image>
				</view>

				<view class="img_box" v-else>
					<image class="img" :src="defaultIcon" mode="aspectFill"></image>
				</view>

				<view class="keytag">
					<text class="keytag_text">{{ key }}</text>
				</view>

				<view class="count" :style="{ background: iconMap[key].color || '#999' }">
					<text class="count_text">{{ value }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { iconMap } from '../utils/shopIcon';

export default {
	name: 'ShopBar',

	computed: {
		shops() {
			// 过滤无效数据
			const validMarkers = this.markers.filter(
				(item) =>
					item && item.keytag !== undefined && item.keytag !== null && item.id !== this.storeData.user.userId && item.keytag !== '普通用户' && item.keytag !== '收藏点'
			);

			return validMarkers.reduce((acc, item) => {
				const keytag = item.keytag;
				acc[keytag] = (acc[keytag] || 0) + 1;
				return acc;
			}, {});
		},
		storeData() {
			return this.$store.state.msg;
		},
		markers(){
					return this.$store.state.msg.markers
				}
		
	},
	watch: {
		// 监听 shops 对象的变化（深度监听，因为对象属性可能新增/删除）
		shops: {
			handler(newShops, oldShops) {
				const newKeys = Object.keys(newShops); // 新 shops 的所有 key
				const oldActive = this.activeItem;

				// 若旧 activeItem 不在新 keys 中，重置为 ''（或默认选中第一个 key）
				if (oldActive && !newKeys.includes(oldActive)) {
					this.activeItem = '';
					// 可选：若需要默认选中第一个 key，可改为：
					// this.activeItem = newKeys.length > 0 ? newKeys[0] : '';
				}
			},
			deep: true,
			immediate: true // 初始化时也执行一次（避免初始状态异常）
		}
	},

	data() {
		return {
			iconMap,
			defaultIcon: '/static/none.png',
			barWidth: 0,
			activeItem: '',
			windowWidth: 0
		};
	},
	mounted() {
	  // 1. 先获取 windowWidth，再计算 barWidth，最后渲染（通过 $nextTick 确保 DOM 同步）
	const res = this.storeData.systemInfo
	 
	      this.windowWidth = res.windowWidth; // 关键：用 res.windowWidth（可用窗口宽度）
	      this.barWidth=(res.windowWidth-40)/3

	
	},
	methods: {

		keyIsState(key) {
			// 明确判断：key 存在且等于 activeItem 才返回 true，否则 false
			return !!key && key === this.activeItem;
		},

		handleImageError(key) {
			if (this.iconMap[key]) {
				this.iconMap[key].url = this.defaultIcon;
			}
		},
		handleItemClick(key, value) {
			if (key === this.activeItem) {
				this.activeItem ="";
			} else {
				this.activeItem = key.trim();
			}
			uni.$emit('scale',18)
			console.log(this.activeItem);
			uni.$emit('keytags', key);
			// const format = encodeURIComponent(JSON.stringify(this.markers));
			//   	uni.navigateTo({
			// 	url: `/pages/membersInfo/membersInfo?membersInfo=${format}&key=${key}`
			// });
		},
		longpress(key, value) {
		
			const format = encodeURIComponent(JSON.stringify(this.markers));
			uni.navigateTo({
				url: `/pages/membersInfo/membersInfo?membersInfo=${format}&key=${key}`
			});
		}
	}
};
</script>

<style lang="scss">
.main {
	padding: 10rpx; // 添加内边距，让边缘元素有间距
	display: flex;
	width: 750rpx;
	flex-direction: column;

	// 左对齐
}
.list-box {
	padding: 10rpx 0rpx; // 添加内边距，让边缘元素有间距
	border-radius: 10rpx;
	display: flex;
	flex-direction: row;
	flex-wrap: wrap;
	gap: 5rpx;
}
.title {
	padding: 0 25rpx;
	position: absolute;
	right: 0;
	top: -20rpx;
	z-index: 9999;
}
.title-txt {
	font-size: 28rpx;
	color: #ccc;
}
.list {
	flex: 1;
	position: relative;
	display: flex;
	flex-direction: row;
	align-items: center;
	margin: 8rpx 4rpx;
	box-shadow: 2rpx 2rpx 5rpx rgba(0, 0, 0, 0.5);
	background-color: rgba(218, 218, 218, 0.9);
	padding: 10rpx 10rpx; // 增加内边距，让内容不拥挤
	border-radius: 20rpx;
	transition: background-color 0.15s ease, transform 0.15s ease;
	-webkit-tap-highlight-color: transparent;
	tap-highlight-color: transparent;
	justify-content: center; // 内容居中
}

.listactive {
	background-color: rgba(255, 85, 127, 0.2);
	// transform: scale(0.85);
}

.img_box {
	width: 30rpx;
	height: 30rpx;
	border-radius: 6rpx;
	overflow: hidden;
}

.img {
	width: 30rpx; // 使用百分比更灵活
	height: 30rpx;
}

.keytag_text {
	font-size: 30rpx;
}

.count {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 30rpx;
	height: 30rpx;
	border-radius: 50%;
}

.count_text {
	color: #fff;
	font-size: 20rpx;
	font-weight: bold;
}
</style>
